/**
 * Copyright (C), 2015-2021, 开度
 * FileName: CustomStringEncryptor
 * Author:   ASUS
 * Date:     2021/8/18 16:50
 * Description: Jasyp加密解密自定义处理
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2021/8/18           1.0              Jasyp加密解密自定义处理
 */
package com.example.spring.security.config;

import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricConfig;
import com.ulisesbocchio.jasyptspringboot.encryptor.SimpleAsymmetricStringEncryptor;
import com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 〈Jasyp加密解密自定义处理〉
 *
 * @author Hezeyu
 * @create 2021/8/18
 * @since 1.0.0
 */
@Component("customStringEncryptor")
@Slf4j
@Data
public class CustomStringEncryptor implements StringEncryptor {

    private String pubKey;

    private String privateKey;

    private SimpleAsymmetricConfig config;

    public CustomStringEncryptor() {
        this.config = new SimpleAsymmetricConfig();
        // 设置密钥类型
        config.setKeyFormat(AsymmetricCryptography.KeyFormat.PEM);
    }

    @Override
    public String encrypt(String s) {
        String decryptedMessage = null;
        config.setPublicKey(pubKey);
        StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
        decryptedMessage = encryptor.encrypt(s);
        return decryptedMessage;
    }

    @Override
    public String decrypt(String s) {
        config.setPrivateKey(privateKey);
        StringEncryptor encryptor = new SimpleAsymmetricStringEncryptor(config);
        String decrypt = encryptor.decrypt(s);
        return decrypt;
    }

    @Value("${jasyptKey.publicKey}")
    public void setPubKey(String pubKey) {
        this.pubKey = pubKey;
    }

    @Value("${jasyptKey.privateKey}")
    public void setPrivateKey(String privateKey) {
        this.privateKey = privateKey;
    }
}
